package com.ysjy.course.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.PromptMessage;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.RandomUtil;
import com.ysjy.course.mapper.CourseClassMapper;
import com.ysjy.course.mapper.CourseMapper;
import com.ysjy.course.model.CourseTime;
import com.ysjy.course.model.OrgCourse;
import com.ysjy.course.model.YsCourseHomeData;
import com.ysjy.course.model.YsCoursePackage;
import com.ysjy.course.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class CourseServiceImpl extends BaseServiceImpl<OrgCourse> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseClassMapper courseClassMapper;

    @Autowired
    public void setMapper(CourseMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Boolean> putCourse(OrgCourse data) throws Exception {
        if (data.getCourseTimeList() == null || data.getCourseTimeList().size() == 0 || data.getTimeNum() == 0){
            return ResultDTO.errorResult("课时列表不能为空！" );
        }
        if (data.getCourseTimeList().size() != data.getTimeNum()){
            return ResultDTO.errorResult("课时列表与课时数不一致！" );
        }
        Date currDate = new Date();
        data.setUpdateTime(currDate);
        if (data.getId() == null){
            data.setUniqueId(DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
            courseMapper.insert(data);
        }else {
            courseMapper.update(data);
            //删除旧课时列表
            courseMapper.delCourseTimes(data.getUniqueId());
        }
        //批量添加课时列表
        List<CourseTime> courseTimeList = new ArrayList<>();
        data.getCourseTimeList().forEach(item -> {
            CourseTime courseTime = new CourseTime();
            courseTime.setTitle(item.getTitle());
            courseTime.setSiteId(data.getSiteId());
            courseTime.setCourseUniqueId(data.getUniqueId());
            courseTime.setCreateTime(currDate);
            courseTimeList.add(courseTime);
        });
//        log.error(JsonUtil.objectToJson(data));
//        log.error(JsonUtil.objectToJson(courseTimeList));
        courseMapper.insertCourseTimeBatch(courseTimeList);
        return ResultDTO.successResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Boolean> putOrgCourse(OrgCourse data) throws Exception {
        if (data.getCourseTimeList() == null || data.getCourseTimeList().size() == 0 || data.getTimeNum() == 0){
            return ResultDTO.errorResult("课时列表不能为空！" );
        }
        if (data.getCourseTimeList().size() != data.getTimeNum()){
            return ResultDTO.errorResult("课时列表与课时数不一致！" );
        }
        Date currDate = new Date();
        data.setUpdateTime(currDate);
        if (data.getId() == null){
            data.setUniqueId(DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
            courseMapper.insertOrgCourse(data);
            courseMapper.gatherNumAdd(data.getCourseUniqueId());
        }else {
            OrgCourse orgCourse = courseMapper.getOrgCourseByUniqueId(data.getUniqueId(),null);
            if (orgCourse == null){
                return ResultDTO.errorResult(PromptMessage.COURSE_IS_NULL);
            }
            if (orgCourse.getUseClass()){
                return ResultDTO.errorResult("已开班课程不能进行编辑！");
            }
            courseMapper.updateOrgCourse(data);
            //删除旧课时列表
            courseMapper.delCourseTimes(data.getUniqueId());
        }
        //批量添加课时列表
        List<CourseTime> courseTimeList = new ArrayList<>();
        data.getCourseTimeList().forEach(item -> {
            CourseTime courseTime = new CourseTime();
            courseTime.setTitle(item.getTitle());
            courseTime.setCourseUniqueId(data.getUniqueId());
            courseTime.setCreateTime(currDate);
            courseTime.setSiteId(data.getSiteId());
            courseTime.setTeacherId(data.getTeacherId());
            courseTimeList.add(courseTime);
        });
        courseMapper.insertCourseTimeBatch(courseTimeList);
        return ResultDTO.successResult();
    }

    @Override
    public void changeShelvesStatus(String ids, Integer shelvesStatus) throws Exception{
        courseMapper.updateShelvesStatus(ids,shelvesStatus);
    }
    @Override
    public void packageChangeShelvesStatus(String ids, Integer shelvesStatus) throws Exception{
        courseMapper.updatePackageShelvesStatus(ids,shelvesStatus);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<OrgCourse> getOrgListByPage(Map<String, Object> params, int pageNo, int pageSize) {
        Page<OrgCourse> page = PageHelper.startPage(pageNo, pageSize,true);
        PageInfo<OrgCourse> pageInfo = new PageInfo<>(courseMapper.getOrgListByPage(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    @Transactional(readOnly = true)
    public OrgCourse getCourseByUniqueId(String uniqueId) {
        OrgCourse orgCourse = courseMapper.getCourseByUniqueId(uniqueId);
        if (orgCourse != null)
            orgCourse.setCourseTimeList(courseMapper.getCourseTimeListByUniqueId(uniqueId));
        return orgCourse;
    }

    @Override
    @Transactional(readOnly = true)
    public OrgCourse getOrgCourseByUniqueId(String uniqueId,Long studentId) {
        OrgCourse orgCourse =  courseMapper.getOrgCourseByUniqueId(uniqueId,studentId);
        if (orgCourse != null){
            orgCourse.initSignUpStatus();
            orgCourse.setCourseTimeList(courseMapper.getCourseTimeListByUniqueId(uniqueId));
        }
        return orgCourse;
    }

    @Override
    public ResultDTO<Boolean> deleteOrgCourseByPrimaryKey(Long id) throws Exception {
        OrgCourse orgCourse =  courseMapper.getOrgCourseById(id);
        if (orgCourse!=null){
            Map<String, Object> params = new HashMap<>();
            params.put("classType",4);
            params.put("serviceUniqueId",orgCourse.getUniqueId());
            CourseClassDto classDto = courseClassMapper.getByMapParams(params);
            if (classDto != null){
                return ResultDTO.errorResult("当前课程已开班，无法进行删除操作");
            }
            courseMapper.deleteOrgCourseByPrimaryKey(id);
            return new ResultDTO<>();
        }else{
            return ResultDTO.errorResult(PromptMessage.COURSE_IS_NULL);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<OrgCourse> getOrgCourseList(Map<String, Object> params) {
        return courseMapper.getOrgCourseList(params);
    }

    @Override
    public Map<String, Object> getCourseCount(HashMap<String, Object> params) {
        return courseMapper.getCourseCount(params);
    }

    @Override
    public YsCourseHomeData getCourseHomeData() {
        return courseMapper.getCourseHomeData();
    }

    @Override
    public ResultDTO<Boolean> putCoursePackage(YsCoursePackage data) {
        Date currDate = new Date();
        data.setUpdateTime(currDate);
        if (data.getId() == null){
            data.setUniqueId(DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
            courseMapper.insertCoursePackage(data);
        }else {
            courseMapper.updateCoursePackage(data);
        }
        return new ResultDTO<>();
    }

    @Override
    @Transactional(readOnly = true)
    public YsCoursePackage getCoursePackageByUniqueId(String uniqueId, Long studentId) {
        YsCoursePackage data = courseMapper.getCoursePackageByUniqueId(uniqueId,studentId);
        if (data!=null) data.initSignUpStatus();
        return data;
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<YsCoursePackage> getCoursePackageListByPage(Map<String, Object> params, int pageNo, int pageSize) {
        Page<YsCoursePackage> page = PageHelper.startPage(pageNo, pageSize,true);
        List<YsCoursePackage>  list = courseMapper.getCoursePackageListByPage(params);

        PageInfo<YsCoursePackage> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }
}
